--- title: "奇怪的电梯" created: 2025-11-28 tags: - 算法 --- # 奇怪的电梯 ## 题目 [奇怪的电梯](https://www.luogu.com.cn/problem/P1135) 呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第 i 层楼($1 \le i \le N$)上有一个数字 K_i($0 \le K_i \le N$)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如: 3, 3, 1, 2, 5 代表了 K_i($K_1=3$, $K_2=3$,……),从 1 楼开始。在 1 楼,按“上”可以到 4 楼,按“下”是不起作用的,因为没有 -2 楼。那么,从 A 楼到 B 楼至少要按几次按钮呢? 输入格式 共二行。 第一行为三个用空格隔开的正整数,表示 N, A, B($1 \le N \le 200$, $1 \le A, B \le N$)。 第二行为 N 个用空格隔开的非负整数,表示 $K_i$。 输出格式 一行,即最少按键次数,若无法到达,则输出 `-1`。 样例 #1 样例输入 #1 ```text 5 1 5 3 3 1 2 5 ``` 样例输出 #1 ```text 3 ``` 提示 对于 $100 \% $ 的数据,$1 \le N \le 200$, $1 \le A, B \le N$,$0 \le K_i \le N$。 本题共 16 个测试点,前 15 个每个测试点 6 分,最后一个测试点 10 分。 ## 思路分析 ![[image-05c5e058.png]] 我的想法是 从第一个楼层开始 有往上走和往下走两种情况(当然也可以不走 但是不走就永远到不了目标楼层) 只要能走(合法)就走到移动后的楼层 再对到达的这个楼层进行往上或往下的选择 直到到达目标楼层 这个过程要维护一个最小的次数 所以多传了一个cnt进来 可能太暴力了 把系统栈给爆了 显示mle ```cpp #include using namespace std; const int N=210; int went[N]; int n,A,B; int res=0x3f3f3f; void dfs(int cur,int cnt){ if(cur==B){ res=min(res,cnt); return; } if(cur-went[cur]>0) dfs(cur-went[cur],cnt+1); if(cur+went[cur]<=n) dfs(cur+went[cur],cnt+1); } int main() { ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); cin>>n>>A>>B; for(int i=1;i<=n;i++){ cin>>went[i]; } dfs(A,0); cout< using namespace std; const int N=210; int went[N]; int n,A,B; int res=0x3f3f3f; bool st[N]; void dfs(int cur,int cnt){ if(cur<0 || cur>n) return; if(cur==B){ res=min(res,cnt); return; } st[cur]=true; if(cur-went[cur]>0 && !st[cur-went[cur]]){ st[cur-went[cur]]=true; dfs(cur-went[cur],cnt+1); st[cur-went[cur]]=false; } if(cur+went[cur]<=n && !st[cur+went[cur]]){ st[cur+went[cur]]=true; dfs(cur+went[cur],cnt+1); st[cur+went[cur]]=false; } } int main() { ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); cin>>n>>A>>B; for(int i=1;i<=n;i++){ cin>>went[i]; } dfs(A,0); if(res==0x3f3f3f){ cout<<"-1"<